var echarts = null;



var intervalTime = 6100; //监控频率
var is_start = true; //已经开始监控

function monitor_task() {
	if (is_start) {
		get_server_data();
    }
	else {
		setTimeout(monitor_task, intervalTime);
	}

}

function get_server_data() {
    //从服务器端加载数据，获取一个主机
    var host = $("#hostselect").val();
  	var ajax = $.ajax({
		type: "POST",
		url: '/server_status_information.json',
		timeout: 5000,
		data: {'type': 'ALL', 'host': host },
		success: do_server_status,
		dataType: 'json',
		async: true,
	});
}

function do_server_status(data) {
	var x_date = (new Date()).toLocaleTimeString().replace(/^\D*/,'');
	if (data.success == 1) {
		//update charts
		var index = 0;
		var servicedate = []
		for(var i in data.data.BASEINFO){
           s = [
              index,        // 系列索引
              data.data.BASEINFO[i],
              false,
              false,
              x_date ]
        servicedate.push(s)
        index ++;
		}
		servicechart.addData(servicedate);

		index = 0;
		servicedate = []
		for(var i in data.data.SERVICEINFO){
           s = [
              0,        // 系列索引
              {
                 name:i,
                 value:[data.data.SERVICEINFO[i]]
              },
              false,
              false
               ]
        servicedate.push(s)
        index ++;
		}
        machinechart.addData(servicedate);
	}
	else {
		//填充空的数据
		servicechart.addData([[0, 0, false, false, x_date ]])
		machinechart.addData([[0, 0, false, false, x_date ]])
	}
	setTimeout(monitor_task, intervalTime);
}



var servicechart = null;
var machinechart = null;
require.config({
    paths: {
        echarts: '/static/res/lib/echarts/'
    }
});
require(
            [
                'echarts',
                'echarts/chart/line',   // 按需加载所需图表，如需动态类型切换功能，别忘了同时加载相应图表
                'echarts/chart/bar',
                'echarts/chart/pie'
            ],
            function (ec) {
                echarts = ec;
                servicechart = draw_chart('service_chart', get_line_option('主机状态', '', ['CPU使用率','内存使用率','磁盘使用率'], '百分比', '%'));
                machinechart = draw_chart('machine_chart', get_pie_option('服务状态', '', ['正常','警告','严重']));

                monitor_task();
            }
        );

function draw_chart(e_id, option) {
	var eChart = echarts.init(document.getElementById(e_id));
	eChart.setOption(option);
	return eChart
}

function get_pie_option(text,subtext,legend){
option = {
    title : {
        text: text,
        subtext: subtext,
        x:'left'
    },
    tooltip : {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
    },
    legend: {
        orient : 'vertical',
        x : 'left',
        data:legend
    },
    toolbox: {
        show : true,
        feature : {
            mark : {show: true},
            dataView : {show: true, readOnly: false},
            magicType : {
                show: true,
                type: ['pie', 'funnel'],
                option: {
                    funnel: {
                        x: '25%',
                        width: '50%',
                        funnelAlign: 'left',
                        max: 1548
                    }
                }
            },
            restore : {show: true},
            saveAsImage : {show: true}
        }
    },
    calculable : true,
    series : [
        {
            name:'访问来源',
            type:'pie',
            radius : '55%',
            center: ['50%', '60%'],
            data:[
                {value:3, name:'NORMAL'},
                {value:3, name:'WARN'},
                {value:1, name:'CRITICAL'}
            ]
        }
    ]
};
return option;
}

//line图
function get_line_option(text, subtext, legend, yAxis_name, y_format) {
	option = {
	    title : {
	        text: text,
	        subtext: subtext
	    },
	    tooltip : {
	        trigger: 'axis'
	    },
	    legend: {
	        data:legend
	    },
	    toolbox: {
	        show : true,
	        feature : {
	            dataView : {show: true, readOnly: false},
	            restore : {show: true},
	            saveAsImage : {show: true}
	        }
	    },
	    dataZoom : {
	        show : false,
	        start : 0,
	        end : 100
	    },
	    xAxis : [{
            type : 'category',
            boundaryGap : true,
            data : (function (){
                var now = new Date();
                var res = [];
                var len = 100;
                while (len--) {
                    res.unshift(now.toLocaleTimeString().replace(/^\D*/,''));
                    now = new Date(now - 2000);
                }
                return res;
            })()
	    }],
	    yAxis : [{
            type : 'value',
            scale: true,
            name : yAxis_name,
            axisLabel : {
                formatter: '{value} ' + y_format
            }
        }],
	    series : []
	};
	var tmp = null;
	var s = null;
	for (var i in legend) {
		tmp = legend[i];
		s = {
            name:tmp,
            type:'line',
            xAxisIndex:0,
            yAxisIndex:0,
            data:(function (){
                var res = [];
                var len = 100;
                while (len--) {
                    res.push(0.0);
                }
                return res;
            })()
        }
		option.series.push(s);
	}
	return option;
}

